<template>
  <div>
    <!-- 目录管理 -->
    <el-card class="box-card">
      <div v-if="isSubject">
        <!-- Breadcrumb 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ this.$route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 华丽的分割线 -->
        <el-divider></el-divider>
      </div>
      <el-row type="flex" justify="space-between">
        <el-col
          :span="7"
          style="color: #606266; font-weight: 700; font-size: 14px"
        >
          目录名称
          <el-input
            v-model="listName"
            style="width: 200px; margin-left: 10px"
          />
        </el-col>
        <el-col
          :span="6"
          style="
            color: #606266;
            font-weight: 700;
            font-size: 14px;
            margin-left: 8px;
          "
        >
          状态
          <el-select
            v-model="statearray"
            placeholder="请选择"
            style="width: 200px; margin-left: 10px"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in array"
              :key="index"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button
            size="small"
            @click="clear"
            style="font-size: 12px; width: 60px"
            >清除</el-button
          >
          <el-button
            size="small"
            type="primary"
            style="font-size: 12px"
            @click="search"
            >搜索</el-button
          >
        </el-col>
        <!-- 返回学科 -->
        <el-col :span="5">
          <el-row type="flex" justify="end">
            <el-button
              type="text"
              size="small"
              style="font-size: 14px"
              @click="$router.back()"
              icon="el-icon-back"
              v-if="isSubject"
              >返回学科</el-button
            >
            <el-button
              size="medium"
              icon="el-icon-edit"
              type="success"
              style="font-size: 13px"
              @click="dialogVisible = true"
            >
              <span style="text-align: center">新增目录</span>
            </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row> </el-row>
      <!-- 分割 -->
      <div class="tips">
        <i class="el-icon-info" />
        <span>数据一共 {{ counts }} 条</span>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column width="100" align="center" type="index" label="序号">
        </el-table-column>
        <el-table-column prop="subjectID" label="所属学科" align="center">
          <template v-slot="scope">
            {{ scope.row.subjectName }}
          </template>
        </el-table-column>
        <el-table-column prop="directoryName" align="center" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" align="center" label="创建者">
        </el-table-column>
        <el-table-column label="创建日期" align="center">
          <template slot-scope="scope">
            <!-- {{ dateFn(scope.row.addDate) }} 网上找的方法-->
            {{ dateFn(scope.row.addDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" align="center" label="面试题数量">
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            已{{ transData(scope.row.state) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="enable(scope.row)">
              <span v-if="scope.row.state == 0">启用</span>
              <span v-else>禁用</span>
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.state === 0"
              @click="edit(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.state === 0 || scope.row.totals !== 0"
              @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        style="text-align: right; margin-top: 16px"
        layout="  prev, pager, next, sizes,jumper"
        :total="counts"
        :page-size="params.pagesize"
        :current-page="params.page"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        v-show="counts"
      >
      </el-pagination>
    </el-card>
    <!-- 新增目录弹框 -->
    <el-dialog
      :title="isEdit ? '修改目录' : '新增目录'"
      :visible.sync="dialogVisible"
      @close="closeFn"
    >
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="所属学科" v-show="!$route.query.id">
          <el-select
            v-model="form.subjectID"
            placeholder="请选择"
            label-width="80px"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in simpleName"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="目录名称"
          style="width: 305px"
          prop="directoryName"
        >
          <el-input v-model="form.directoryName"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button  @click="closeFn">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// import { list as getCompanys } from '@/api/hmmm/companys'
// import { list as getQuestion } from '@/api/hmmm/questions'
import { list, remove, update, add, changeState } from '@/api/hmmm/directorys'
import { simple } from '../../api/hmmm/subjects'
import { status } from '../../api/hmmm/constants'
import { parseTime } from '../../utils/index'
export default {
  data () {
    return {
      isSubject: false, // 从学科跳转过来才显示的功能
      subjectName: '',
      array: status, // 循环  列表中 选择 状态
      listName: '',
      statearray: '', // 状态
      isEdit: false, // 是否处于编辑状态
      region: '', // 目录名
      dialogVisible: false, // 弹框
      form: {
        //    表单
        subjectID: '', // 科目名
        directoryName: ''
      },
      rules: {
        directoryName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      simpleName: [], // 所属学科(新增按钮)
      tableData: [
        // 表格
      ],
      params: {
        pagesize: 10, // 总页数
        page: 1 // 当前页码
      },
      counts: 0, // 总条数
      curId: ''
    }
  },
  created () {
    // getCompanys()
    // getQuestion()
    this.simple()
    // if (this.isShow === false) {
    //   this.change()
    // }
    // console.log('id', this.$route.query.id, this.$route.query.name)
    // 跳转学科
    if (this.$route.query.id) {
      this.isSubject = true
      this.loadList({
        subjectID: this.$route.query.id,
        subjectName: this.$route.query.name
      })
    } else {
      this.isSubject = false
      // console.log(2)
      this.loadList()
    }
  },
  methods: {
    // 点击
    submit () {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        this.isEdit ? this.doedit() : this.Add()
      })
    },
    async Add () {
      this.isEdit = false
      if (this.$route.query.id) { // 从学科来的弹框里新增项
        const data = {
          subjectID: Number(this.$route.query.id),
          directoryName: this.form.directoryName
        }
        const re = await add(data)
        console.log(re)
      } else {
        this.isSubject = true
        const res = await add({
          ...this.form,
          subjectID: this.form.subjectID,
          directoryName: this.form.directoryName
        })
        console.log('添加目录', res)
      }
      this.$message.success('操作成功')
      this.loadList()
      this.closeFn()
    },
    // 所属学科(新增按钮)
    async simple () {
      const re = await simple()
      console.log('简单', re)
      this.simpleName = re.data
    },
    // 删除
    del (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async doDel (row) {
      const res = await remove(row)
      console.log('删除的目录列表项', res)
      console.log('删除的目录列表项', this.listName)
      const re = await list({
        // ...this.params,
        directoryName: this.listName,
        state: this.statearray
      })
      console.log('删除的目录列表项', re)
      this.tableData = re.data.items // 重新获取一遍当前列表
      this.counts = re.data.counts
    },
    // 修改
    edit (row) {
      this.dialogVisible = true
      this.isEdit = true
      this.form = row
      console.log('要修改项', row)
    },
    async doedit () {
      const res = await update({
        ...this.form,
        subjectID: this.form.subjectID,
        directoryName: this.form.directoryName
      })
      console.log('修改列表', res)
      const re = await list({
        ...this.params,
        directoryName: this.listName,
        state: this.statearray
      })
      console.log(re)
      this.tableData = re.data.items // 重新获取一遍当前列表
      this.closeFn()
      this.$message.success('操作成功')
    },
    // 详细列表
    async loadList () {
      let res = null
      if (this.listName && this.listName !== undefined) {
        res = await list({
          ...this.params,
          directoryName: this.listName,
          state: this.statearray
        })
        console.log(11)
      } else {
        res = await list(this.params)
      }

      this.tableData = res.data.items
      this.counts = res.data.counts
      this.subjectName = res.data.items.subjectName
      console.log('目录列表', res, res.data.counts, this.subjectName)
      // this.simpleName = res.data.items
    },
    // 关闭
    closeFn () {
      this.form.subjectID = ''
      this.form.directoryName = ''
      this.form = {}
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    //  搜索按钮
    async search () {
      console.log(this.listName, this.statearray)
      this.params.page = 1 // 调回第一页
      this.loadList()
    },
    // 清除按钮
    clear () {
      this.listName = ''
      this.statearray = ''
      this.loadList()
    },
    // 开启/关闭  的转换
    async enable (val) {
      console.log(val)
      try {
        await changeState({
          ...val,
          state: val.state === 1 ? 0 : 1
        })
        this.loadList()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    transData (arr) {
      // 把state中的1改成正式， 2改成非正式
      // console.log('state的值', arr)

      const statusObj = {} // {1: "启用", 2: "禁用"}
      status.forEach((item) => {
        statusObj[item.value] = item.label
      })
      // 枚举
      // console.log('常量对象保存的状态', status)
      return statusObj[arr]
    },
    // 改变时间样式
    dateFn (date) {
      // 方法一 调用时间方法
      const res = parseTime(date)
      return res
      // console.log(res)
      // 方法二
    //   // console.log('时间', date)
    //   var jsondate = new Date(date).toJSON()
    //   return new Date(new Date(jsondate) + 8 * 3600 * 1000)
    //     .toISOString()
    //     .replace(/T/g, ' ')
    //     .replace(/\.[\d]{3}Z/, '')
    },
    // 分页
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.params.page = newPage
      if (this.$route.query.name) {
        this.loadList()
      } else {
        this.loadList()
      }
    },
    // 条数
    handleSizeChange (newSize) {
      console.log(newSize)
      this.params.pagesize = newSize
      if (this.$route.query.name) {
        this.loadList()
      } else {
        this.loadList()
      }
    }
  },
  computed: {
    status () {
      return status
    }
  }
}
</script>

<style scoped lang='scss'>
.el-card {
  margin: 10px;
  .tips {
    margin-top: 16px;
    line-height: 34px;
    padding: 0px 15px;
    font-weight: normal;
    font-size: 14px;
    border-radius: 5px;
    color: #909399;
    background: #eee;
    i {
      margin-right: 10px;
      color: #909399;
    }
  }
}
</style>
